package com.example.diethealthsystem.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object loggedInUser = session.getAttribute("loggedInUser");

        logger.info("AuthInterceptor: Request URI: {}", request.getRequestURI());
        logger.info("AuthInterceptor: loggedInUser in session: {}", loggedInUser != null ? ((com.example.diethealthsystem.entity.User)loggedInUser).getUsername() : "null");

        // 如果用户未登录且访问的不是登录或注册页面，则重定向到登录页面
        if (loggedInUser == null &&
            !request.getRequestURI().equals("/login") &&
            !request.getRequestURI().equals("/register") &&
            !request.getRequestURI().startsWith("/css/") && // 允许访问CSS
            !request.getRequestURI().startsWith("/js/") && // 允许访问JS
            !request.getRequestURI().startsWith("/images/") && // 允许访问图片
            !request.getRequestURI().startsWith("/error")) { // 允许访问错误页面
            response.sendRedirect("/login");
            return false; // 阻止后续处理
        }
        return true; // 继续处理请求
    }
} 